package com.wondream.myframework.app.common.config.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


/**
 * @author wondream
 * @version 1.0
 * @create 2022/11/16 9:04 PM
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    Logger logger = LoggerFactory.getLogger(DynamicDataSource.class);

    /**
     * 构造注入
     * 加载配置文件时创建
     * @param masterDataSource
     * @param slaveDataSource
     */
    public DynamicDataSource(DataSource masterDataSource, DataSource slaveDataSource) {
        super.setDefaultTargetDataSource(masterDataSource);
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("masterDataSource", masterDataSource);
        targetDataSources.put("slaveDataSource", slaveDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }


    /**
     * 设置当前数据源入口
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceHolder.getCurrent();
    }
}
